package com.quanyue.music.support;

import com.google.common.base.Charsets;
import com.quanyue.auto.cache.CacheService;
import com.quanyue.auto.util.AssertUtils;
import com.quanyue.auto.web.Principal;
import com.quanyue.auto.web.UserDetailService;
import com.quanyue.auto.web.WebProperties;
import com.quanyue.music.domain.constant.UserRole;
import com.quanyue.music.domain.entity.Manager;
import com.quanyue.music.user.service.ManagerService;
import com.quanyue.music.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Base64;
import java.util.Set;

@Service
public class UserDetailServiceImpl implements UserDetailService {

    private final UserService userService;
    private final ManagerService managerService;
    private final CacheService cacheService;
    private final WebProperties properties;

    @Autowired
    public UserDetailServiceImpl(UserService userService,
                                 ManagerService managerService,
                                 CacheService cacheService,
                                 WebProperties properties) {
        this.userService = userService;
        this.managerService = managerService;
        this.cacheService = cacheService;
        this.properties = properties;
    }

    @Override
    public Object findUser(Principal contextUser) {
        if (contextUser.getRole().equals(UserRole.USER)) {
            return userService.findById(contextUser.getId());
        } else if (contextUser.getRole().equals(UserRole.USER)) {
            return managerService.findById(contextUser.getId());
        }
        return null;
    }

    @Override
    public Principal findPrincipal(String token) {
        if (token.length() == 32) {
            return cacheService.get(properties.getCacheKey(), token);
        } else {
            String[] codes = new String(Base64.getDecoder().decode(token), Charsets.UTF_8).split(",");
            AssertUtils.isTrue(codes.length == 2, "非法访问");
            Manager manager = managerService.findById(codes[1]);
            if (manager == null) {
                return null;
            }
            Principal principal = new Principal();
            principal.setId(manager.getId());
            principal.setMerchantNo(10100);
            principal.setRole(UserRole.MANAGER);
            return principal;
        }
    }

    @Override
    public Set<String> findPrimitives(Principal principal) {
        return null;
    }
}
